<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2020 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\View;
use app\addons\File;
use app\admin\BaseController;
/**
 * 语言管理
 */
class Lang extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $this->path    = public_path() . 'lang/';
        $this->default = include($this->path . $this->request->langDefault . '.php');
    }

    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input();
            $list  = unserialize(config('app.language'));
            foreach ($list as $key => $val) {
                // 参数读取
                $filename  = $this->path . $val['name'] . '.php'; 
                $parameter = is_file($filename) ? include($filename) : [];
                $list[$key]['parameter'] = [];
                foreach ($this->default as $k => $v) {
                    $arr['title'] = $k;
                    $arr['value'] = isset($parameter[$k]) ? $parameter[$k] : "";
                    array_push($list[$key]['parameter'], $arr);
                }
            }
            $data = array_sort($list, 'sort');
            return json(['status' => 'success', 'message' => '获取成功', 'data' => $data]);
        } else {
            return View::fetch();
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            $data  = $input['value'];
            foreach ($data as $key => $val) {
                $filename  = $this->path . $val['name'] . '.php';
                $parameter = [];
                foreach ($val['parameter'] as $k => $v) {
                    $parameter[$v['title']] = $v['value'];
                }
                $content = "<?php\nreturn ".var_export($parameter,true).";";
                File::create($filename, $content);
                unset($data[$key]['parameter']);
            }
            $pat[] = 'language';
            $rep[] = serialize($data);
            File::editConfig($pat, $rep, config_path().'app.php');
            return json(['status' => 'success', 'message' => '操作成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
}